﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.Script.Services;
using Newtonsoft.Json;
using System.Configuration;
using System.Data;

namespace PromotionEngine
{
    public partial class DocLine : System.Web.UI.Page
    {
        public class Response
        {
            public List<Model.DocLine> Data { get; set; }
            public int Count { get; set; }
            public string Errors { get; set; }

            public Response(List<Model.DocLine> data, int count)
            {
                this.Data = data;
                this.Count = count;
            }

            public Response(string errors)
            {
                this.Errors = errors;
            }

            public Response()
            {

            }
        }
        protected void Page_PreInit(object sender, EventArgs e)
        {
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }
        }
        [WebMethod]
        public static string GetLastRecord()
        {
            Promotion pmt = new Promotion();
            DataSet dsPromotion = pmt.GetLastRecordDocHeader(ConfigurationManager.AppSettings["DATABASE_NAME"].ToString(), HttpContext.Current.Session["CompanyCode"].ToString());
            if (dsPromotion != null)
            {
                return JsonConvert.SerializeObject(dsPromotion);
            }
            return string.Empty;
        }
        [WebMethod]
        public static string GetDocHeaderByDocEntry(string docEntry)
        {
            Promotion pmt = new Promotion();
            DataSet dsPromotion = pmt.GetDocHeaderByDocEntry(ConfigurationManager.AppSettings["DATABASE_NAME"].ToString(),HttpContext.Current.Session["CompanyCode"].ToString(), docEntry);
            if (dsPromotion != null)
            {
                return JsonConvert.SerializeObject(dsPromotion);
            }
            return string.Empty;
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static string ClosedDoc(string docEntry)
        {
            Promotion pmt = new Promotion();
            string errMsg = pmt.ClosedMarketingDocument(ConfigurationManager.AppSettings["DATABASE_NAME"].ToString(), docEntry, "2");

            if (Utils.Utils.IsNumberInteger(errMsg))
            {
                List<Model.DocLine> lstDocLine = new List<Model.DocLine>();
                if (HttpContext.Current.Session["DocList"] != null)
                {
                    lstDocLine = (List<Model.DocLine>)HttpContext.Current.Session["DocList"];
                    foreach (Model.DocLine docLine in lstDocLine)
                    {
                        docLine.DocStatus = "2";
                    }
                    HttpContext.Current.Session["DocList"] = lstDocLine;
                }
            }

            return errMsg;
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public static Response GetDocLines(string docEntry)
        {
            if (HttpContext.Current.Session["DocList"] != null)
            {
                List<Model.DocLine> lstDocLineUpdate = (List<Model.DocLine>)HttpContext.Current.Session["DocList"];
                List<Model.DocLine> filteredResults = lstDocLineUpdate.FindAll(p => p.LineStatus != "3");
                HttpContext.Current.Session["DocList"] = filteredResults;
                HttpContext.Current.Session["DocCount"] = filteredResults.Count;
                return new Response(filteredResults, filteredResults.Count);
            }
            List<Model.DocLine> lstDocLine = new List<Model.DocLine>();
            Promotion pmt = new Promotion();
            DataSet dsPromotion = pmt.GetDocLineByDocEntry(ConfigurationManager.AppSettings["DATABASE_NAME"].ToString(), docEntry);
            if (dsPromotion != null)
            {
                foreach (DataRow r in dsPromotion.Tables[0].Rows)
                {
                    Model.DocLine docLine = new Model.DocLine();
                    docLine.DocEntry = r["DocEntry"].ToString();
                    docLine.ItemID = r["ItemID"].ToString();
                    docLine.ItemCode = r["ItemCode"].ToString();
                    docLine.ItemName = r["ItemName"].ToString();
                    docLine.LineNum = r["LineNum"].ToString();
                    docLine.Quantity = double.Parse(r["Quantity"].ToString());
                    docLine.WarehouseID = r["WarehouseID"].ToString();
                    docLine.WarehouseName = r["WarehouseName"].ToString();
                    docLine.BasePrice = double.Parse(r["BasePrice"].ToString());
                    docLine.LineTotal = double.Parse(r["LineTotal"].ToString());
                    docLine.LineStatus = "2";
                    docLine.DocStatus = r["DocStatus"].ToString();
                    docLine.SalesPersonID = r["SalesPersonID"].ToString();
                    docLine.SalesPersonCode = r["SalesPersonCode"].ToString();
                    docLine.SalesPersonName = r["SalesPersonName"].ToString();
                    docLine.DiscountAmount = double.Parse(r["DiscountAmount"].ToString());
                    docLine.TotalAfterDiscount = double.Parse(r["TotalAfterDiscount"].ToString());
                    docLine.ItemType = r["ItemType"].ToString();
                    docLine.ReferenceName = r["ReferenceName"].ToString();
                    lstDocLine.Add(docLine);
                }
                HttpContext.Current.Session["DocList"] = lstDocLine;
                HttpContext.Current.Session["DocCount"] = dsPromotion.Tables[0].Rows.Count;
                var jsonData = new { total = dsPromotion.Tables[0].Rows.Count, lstCustomerProperty = lstDocLine };
                return new Response(lstDocLine, dsPromotion.Tables[0].Rows.Count);
            }
            return new Response();
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static void UpdateDoc(string oDocLine, string isInsert, string rowIndex)
        {
            Model.DocLine line = JsonConvert.DeserializeObject<Model.DocLine>(oDocLine);
            if (HttpContext.Current.Session["DocList"] != null)
            {
                List<Model.DocLine> lstDocLine = (List<Model.DocLine>)HttpContext.Current.Session["DocList"];
                var result = (from m in lstDocLine
                              select m).OrderByDescending(a => a.LineNum).FirstOrDefault(); ;
                if (isInsert == "1")
                {
                    if (result != null)
                    {
                        line.LineNum = (int.Parse(result.LineNum) + 1).ToString();
                    }
                    else
                    {
                        line.LineNum = "1";
                    }
                    line.LineStatus = "1";
                    lstDocLine.Add(line);
                }
                else if (isInsert == "2")
                {
                    line.LineStatus = "2";

                    Model.DocLine updateLine = lstDocLine.FirstOrDefault(u => u.LineNum == line.LineNum);
                    int index = lstDocLine.FindIndex(u => u.LineNum == line.LineNum);
                    updateLine.ItemID = line.ItemID;
                    updateLine.ItemCode = line.ItemCode;
                    updateLine.ItemName = line.ItemName;
                    updateLine.Quantity = line.Quantity;
                    updateLine.WarehouseID = line.WarehouseID;
                    updateLine.WarehouseName = line.WarehouseName;
                    updateLine.BasePrice = line.BasePrice;
                    updateLine.LineTotal = line.LineTotal;
                    updateLine.SalesPersonID = line.SalesPersonID;
                    updateLine.SalesPersonName = line.SalesPersonName;
                    updateLine.SalesPersonCode = line.SalesPersonCode;
                    updateLine.TotalAfterDiscount = line.TotalAfterDiscount;
                    updateLine.DiscountAmount = line.DiscountAmount;
                    updateLine.ItemType = line.ItemType;
                    updateLine.ReferenceName = line.ReferenceName;
                }
                HttpContext.Current.Session["DocList"] = lstDocLine;
                HttpContext.Current.Session["DocCount"] = lstDocLine.Count;
            }
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public static void DeleteDocLine(string lineNum)
        {
            if (HttpContext.Current.Session["DocList"] != null)
            {
                List<Model.DocLine> lstDocLine = (List<Model.DocLine>)HttpContext.Current.Session["DocList"];
                Model.DocLine updateLine = lstDocLine.FirstOrDefault(u => u.LineNum == lineNum);
                if (updateLine.DocEntry.Length > 0)
                {
                    updateLine.LineStatus = "3";
                }
                else
                {
                    lstDocLine.Remove(updateLine);
                }
                HttpContext.Current.Session["DocList"] = lstDocLine;
                HttpContext.Current.Session["DocCount"] = lstDocLine.Count;
            }
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static string UpdateDocToDB(string oDocHeader, bool isUpdate)
        {
            Model.DocHeader header = JsonConvert.DeserializeObject<Model.DocHeader>(oDocHeader);
            List<Model.DocLine> lstDocLine = new List<Model.DocLine>();
            if (HttpContext.Current.Session["DocList"] != null)
            {
                lstDocLine = (List<Model.DocLine>)HttpContext.Current.Session["DocList"];
            }
            if (header != null)
            {
                if (HttpContext.Current.Session["LoginUser"] != null)
                {
                    DataTable tbUser = (DataTable)HttpContext.Current.Session["LoginUser"];

                    if (tbUser != null && tbUser.Rows.Count > 0)
                    {
                        header.CreatedUserID = tbUser.Rows[0]["UserID"].ToString();
                        header.CompanyCode = tbUser.Rows[0]["CompanyCode"].ToString();
                    }
                }
                if (isUpdate == false)
                {
                    header.DocStatus = 1;
                }
                if (lstDocLine.Count > 0)
                {
                    Promotion pmt = new Promotion();
                    string headerJson = JsonConvert.SerializeObject(header);
                    string lineJson = JsonConvert.SerializeObject(lstDocLine);
                    string errMsg = pmt.CreateMarketingDocument(ConfigurationManager.AppSettings["DATABASE_NAME"].ToString(), header.DocEntry, isUpdate, headerJson, lineJson);
                    return errMsg;
                }
                else
                {
                    return "Please input item.";
                }
            }
            return "0";
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static void ClearSessionData()
        {
            HttpContext.Current.Session["DocList"] = null;
            HttpContext.Current.Session["DocCount"] = null;
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public static string GetAllReferenceValueItemType()
        {
            List<Model.ReferenceTypeValue> lstReferenceValue = new List<Model.ReferenceTypeValue>();
            Promotion pmt = new Promotion();
            DataSet dsPromotion = pmt.GetReferenceValue(ConfigurationManager.AppSettings["DATABASE_NAME"].ToString(), "ItemType");
            if (dsPromotion != null && dsPromotion.Tables.Count > 0)
            {
                return JsonConvert.SerializeObject(dsPromotion.Tables[0]);

            }
            return string.Empty;
        }
        [WebMethod]
        public static string GetItems()
        {
            Promotion pmt = new Promotion();
            DataSet dsPromotion = pmt.GetAllItem(ConfigurationManager.AppSettings["DATABASE_NAME"].ToString(), HttpContext.Current.Session["CompanyCode"].ToString(),
                bool.Parse(HttpContext.Current.Session["IsAdmin"].ToString()));
            if (dsPromotion != null)
            {
                return JsonConvert.SerializeObject(dsPromotion.Tables[0]);
            }
            return string.Empty;
        }
    }
}
